import React, { Component } from 'react';
import { Modal, message, Button, Spin, DatePicker, Radio } from 'antd';
import moment from 'moment';
import './index.scss';
import fetch from '../../../util/fetch'
import { getQueryVariable } from '../../../util/public'
import $ from 'jquery';
// import UEditor from '../UEditor';
import WangEditor from '../WangEditor';
import { Scrollbars } from 'react-custom-scrollbars';
import { LgPickerDialog } from '../pickerDialog/index.tsx'
import Base64 from '../../../util/base64'
const BYTES_PER_SLICE = 1024 * 1024;
const FILETYPE = ['', '文档', '图片', '音频', '视频', '其他']

class CreateNotice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            objectList: [],
            noticeTitle: '',
            id: '',
            AttachmentUrl: '',
            AttachmentName: '',
            AttachmentSize: '',
            AttachmentType: '',
            isupload: false,
            serverTime: '',
            TemplateList: [],
            NoticeMain: 0,
            visible4: false,
            NoticeID: '',
            loading: false,
            ImportClick: false,
            sysID: 400,
            iFrame: false,
            isFrame: false,
            isshowCommonWord: false,
            commonWordName: '',
            commonWordContent: '',
            commonWord: {},
            commonWordType: 'add',
            currentTemplateID: '',
            childIsShow: false,
            sendAgainText: "",
            isCreateAgain: true,
            TermEndDate: "",
            identityCode: "",

            // 新选择对象
            isShowPickerDialog: false,
            selectedList: [],
            treeList: [],

            // 新增楼牌选择 2023-09-06  start
            equipVisible: false,
            equipList: [],
            chooseDeviceList: [],
            selectDeviceList: [],

            // 类型
            contentType: "1",
            // 是否公开
            noticeType: "1",

            // 富文本框
            editorValue: "",
        };
        this.CloseNotice = this.CloseNotice.bind(this);
    }
    componentDidMount(){
        let {
            noticeId
        } = this.props;
        if(noticeId){
            this.setState({
                loading: true
            })
            fetch.get({
                url: window.BasicProxy + 'api/notice/info/edit/detail',
                params: {
                    noticeId,
                    eduId: sessionStorage.getItem("eduId"),
                }
            })
            .then((res)=>res.json())
            .then((result)=>{
                if(result.code === "200" && result.data){
                    let data = result.data;
                    //需要将选择对象还原成可识别的数组
                    let fileObj = {}, selectedList = [], deviceList = [];
                    if(Array.isArray(data.attachments) && data.attachments.length != 0){
                        let attachment = data.attachments[0]
                        fileObj = {
                            AttachmentName: attachment.name,
                            AttachmentSize: attachment.size,
                            AttachmentType: attachment.type,
                            AttachmentUrl: attachment.url
                        }
                    }
                    // 楼牌
                    if(Array.isArray(data.deviceList) && data.deviceList.length > 0){
                      deviceList = data.deviceList.map(item => {
                        item.buildingBoardId = item.deviceId;
                        item.buildingBoardName = item.deviceName;
                        item.buildingBoardType = item.deviceType;
                        return item
                      })
                    }
                    Array.isArray(result.data.receivers) && result.data.receivers.forEach(item => {
                        item.label = item.schoolName + item.identityName
                        item._itemId = item.schoolId + "-" + (item.identityId || item.identityCode)
                        selectedList.push(item)
                    })
                    this.setState({
                        noticeTitle: data.title,
                        ...fileObj,
                        selectedList,
                        receiverType: data.receiverType,
                        editNoticeId: data.noticeId,
                        contentType: data.contentType || "1",
                        chooseDeviceList: deviceList,
                        selectDeviceList: deviceList,
                        editorValue: data.content,
                    })
                } else {
                    message.warn(result.msg);
                }
                this.setState({
                    loading: false
                })
            })
        }

        this.getEquip()
    }

    /** 新增楼牌选择 2023-09-06  start */ 
    getEquip = () => {
        let obj = {
          eduId: sessionStorage.getItem("eduId") || "",
        }
        fetch.get({
            url: window.BasicProxy + '/api/commons/school/device/building/boards',
            params: obj
        }).then(res => {
            return res.json()
        }).then(json => {
            if (json.code == 200) {
                let seleArr = this.state.selectDeviceList.concat([]);
                let list = json.data;
                list.forEach(element => {
                    let seleNum = seleArr.filter(itm => itm.schoolId === element.schoolId).length;
                    if (seleNum === element.buildingBoardList.length) {
                        element.buildSign = 'active'
                    } else if (seleNum > 0 && seleNum < element.buildingBoardList.length) {
                        element.buildSign = 'contain'
                    } else {
                        element.buildSign = 'no'
                    }
                    element.showEquip = false
                    // element.buildSign = 'no'
                    element.buildingBoardList.forEach(item => {
                        item.schoolId = element.schoolId
                        item.schoolName = element.schoolName
                    })
                });
                this.setState({
                  chooseDeviceList: seleArr,
                  equipList: list,
                })
            } else {
                message.error(json.msg, 3)
            }
        })
    }
    showEquipList = (equip, index) => {
        let equipArr = this.state.equipList.concat([]);
        equipArr[index].showEquip = !equip;
        this.setState({ equipList: equipArr })
    }
    // 打开楼牌弹窗
    openDeviceModal = () => {
      let equipList = this.state.equipList.concat([])
      equipList.forEach(item => {
        if(["active", "contain"].includes(item.buildSign)){
          item.showEquip = true
        }else{
          item.showEquip = false
        }
      })
      this.setState({
        chooseDeviceList: this.state.selectDeviceList.concat([]),
        equipList,
        equipVisible: true
      })
    }
    // 重新选择楼牌
    reChooseDevice = () => {
      this.state.equipList.forEach(item => {
        item.buildSign = "no"
      })
      this.setState({
        selectDeviceList: [],
        chooseDeviceList: [],
      }, this.openDeviceModal)
    }
    // 全选楼牌
    allChecked = (item, index) => {
        let arr = this.state.equipList.concat([]);
        let chooseArr = this.state.chooseDeviceList.concat([]);
        if (item.buildSign == 'no' || item.buildSign == 'contain') {
            arr[index].buildSign = 'active'
            for (let i = 0; i < item.buildingBoardList.length; i++) {
                chooseArr.push(item.buildingBoardList[i]);
            }
        } else {
            arr[index].buildSign = 'no'
            chooseArr = chooseArr.filter(itm => itm.schoolId !== item.schoolId);
        }
        // 去重
        chooseArr = [...new Set(chooseArr.map(JSON.stringify))].map(JSON.parse);
        this.setState({
          equipList: arr,
          chooseDeviceList: chooseArr
        })
    }
    // 选择楼牌
    chooseDevice = (obj, item1) => {
        let chooseArr = this.state.chooseDeviceList.concat([]);
        let sign = 0;  // 0是添加， 1是删除
        let delIndex;
        chooseArr.forEach((item) => {
            if (item.buildingBoardId === obj.buildingBoardId && item.schoolId === obj.schoolId) { //已存在
                sign = 1;
            }
        })
        if (sign === 0) {
            chooseArr.push(obj);
        } else {
            delIndex = chooseArr.findIndex(item => item.buildingBoardId === obj.buildingBoardId && item.schoolId === obj.schoolId);
            chooseArr.splice(delIndex, 1);
        }
        let seleNum = chooseArr.filter(itm => itm.schoolId === item1.schoolId).length;
        if (seleNum === item1.buildingBoardList.length) {
            item1.buildSign = 'active'
        } else if (seleNum > 0 && seleNum < item1.buildingBoardList.length) {
            item1.buildSign = 'contain'
        } else {
            item1.buildSign = 'no'
        }
        this.setState({ chooseDeviceList: chooseArr })
    }
    // 删除所选楼牌
    deleteDevice = (index, item1) => {
        let chooseArr = this.state.chooseDeviceList.concat([]);
        chooseArr.splice(index, 1);
        let seleNum = chooseArr.filter(itm => itm.schoolId === item1.schoolId).length;
        if (seleNum === item1.buildingBoardList.length) {
            item1.buildSign = 'active'
        } else if (seleNum > 0 && seleNum < item1.buildingBoardList.length) {
            item1.buildSign = 'contain'
        } else {
            item1.buildSign = 'no'
        }
        this.setState({ chooseDeviceList: chooseArr })
    }
    // 确定选择楼牌
    confirmSle = () => {
        let chooseArr = this.state.chooseDeviceList.concat([]);
        this.setState({
          selectDeviceList: chooseArr,
          equipVisible: false
        })
    }
    // 取消选择楼牌
    cancelSle = () => {
        this.setState({
          chooseDeviceList: [],
          equipVisible: false
        })
    }
    // 删除选择框外的已选择楼牌
    delSelect = (index) => {
        let seleArr = this.state.selectDeviceList.concat([]);
        let equipList = this.state.equipList.concat([])
        seleArr.splice(index, 1);
        equipList.forEach(element => {
            let seleNum = seleArr.filter(itm => itm.schoolId === element.schoolId).length;
            if (seleNum === element.buildingBoardList.length) {
                element.buildSign = 'active'
                element.showEquip = true
            } else if (seleNum > 0 && seleNum < element.buildingBoardList.length) {
                element.buildSign = 'contain'
                element.showEquip = true
            } else {
                element.buildSign = 'no'
                element.showEquip = false
            }
            element.buildingBoardList.forEach(item => {
                item.schoolId = element.schoolId
                item.schoolName = element.schoolName
            })
        });
        this.setState({ 
          selectDeviceList: seleArr, 
          chooseDeviceList: seleArr,
          equipList
        })
    }
    /** 新增楼牌选择 2023-09-06  end */

    // 修改类型
    changeContentType = (e) => {
      let value = e.target.value
      if(value === this.state.contentType){
        return
      }
      this.setState({
        contentType: value,
        AttachmentUrl: "",
        AttachmentName: "",
        AttachmentSize: "",
        AttachmentType: "",
      })
    }
    // 修改是否公开
    changeNoticeType = (e) => {
      let value = e.target.value
      if(value === this.state.noticeType){
        return
      }
      this.setState({
        noticeType: value,
      })
    }

    // 预览文件
    prevFile = (url) => {
      let webSvrAddr = JSON.parse(sessionStorage.getItem("sysAddrInfo") || "{}")["U10"]
      let schoolId = sessionStorage.getItem("eduId")
      let base64 = new Base64()
      url = url?.includes("http")? url: (window.BasicProxy + url)
      url = encodeURIComponent(base64.encode(url))
      window.open(`${webSvrAddr}onlinePreview?url=${url}&schoolId=${schoolId}`)
    }

    changeNoticeTitle(e) {

        this.setState({
            noticeTitle: e.target.value
        })
    }
    uploadFile() {

        let $this = this;
        let file = $('#file')[0].files[0];
        // console.log('file',file)
        if (!file) {
            $this.setState({
                AttachmentUrl: '',
                AttachmentName: '',
                AttachmentSize: '',
                AttachmentType: '',
            })
            $('#file').val('');
            return;
        }
        if (file.size > 1024 * 1024 * 50) {
            message.error('上传附件不能大于50MB~');
            $this.setState({
                AttachmentUrl: '',
                AttachmentName: '',
                AttachmentSize: '',
                AttachmentType: '',
            })
            $('#file').val('');
            return;
        }
        let uploadType = ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'mp3', 'mp4', 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'cab', 'iso', 'mp4', 'mp3', 'txt', 'doc', 'docx', 'docs', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
        if(this.state.contentType == 2){
          uploadType = ['bmp', 'gif', 'mp3', 'mp4']
        }
        if (uploadType.indexOf(file.name.slice(file.name.lastIndexOf('.') + 1, file.name.length)) === -1) {
            message.error('上传文件格式不正确~');
            $this.setState({
                AttachmentUrl: '',
                AttachmentName: '',
                AttachmentSize: '',
                AttachmentType: '',
            })
            $('#file').val('');
            return;
        }
        $this.setState({
            isupload: 'true',
        })
        let formData = new FormData()
        formData.append("file", file)
        formData.append("modelName", "notice")
        $.ajax({
            url: window.BasicProxy + "api/commons/file/upload",
            type: "post",
            async: true,
            data: formData,
            dataType:'json',
            cache: false, // 上传文件无需缓存
            processData : false, // 使数据不做处理
            contentType: false, //不额外设置请求头
            headers: {
                "Authorization": sessionStorage.getItem("token") || getQueryVariable("lg_tk"),
            },
            success: (res)=>{
                if(res.code === "200" && Array.isArray(res.data)){
                    let data = res.data[0]
                    $this.setState({
                        AttachmentUrl: data.url,
                        AttachmentName: data.fileName,
                        AttachmentSize: data.size,
                        AttachmentType: FILETYPE.indexOf(data.type) != -1? FILETYPE.indexOf(data.type): 5,
                        isupload: false,
                    })
                    message.success({content: "上传成功", key: 'tip'})
                }
            },
            error: (res)=>{
                message.error(res.msg);
            }
        })
    }
    uploadDel = (e) => {
        this.setState({
            AttachmentName: '',
            AttachmentSize: '',
            AttachmentUrl: '',
            AttachmentType: '',
        })
        e.stopPropagation()
    }
    // 预览
    onoK4() {
        if (this.state.editorValue) {
            let myDate = new Date();
            let year = myDate.getFullYear();    //获取完整的年份(4位,1970-????)
            let Month = myDate.getMonth() * 1 + 1;       //获取当前月份(0-11,0代表1月)
            let Date1 = myDate.getDate();
            let Hours = myDate.getHours();       //获取当前小时数(0-23)
            let Minutes = myDate.getMinutes();
            this.setState({
                visible4: true,
                serverTime: year + '-' + Month + '-' + Date1 + ' ' + Hours + ':' + Minutes
            })
        } else {
            message.error('通知内容不能为空~');
        }

    }
    // 关闭预览弹窗
    handleCancel4 = () => {
        this.setState({
            visible4: false
        })
    }
    // 关闭发布通知公告弹窗
    CloseNotice = () => {
        this.props.changeVisible(false);
        this.Initialization();
    }
    // 恢复默认参数
    Initialization() {
        $('#file').val('');
        this.setState(
            {
                visible: false,
                noticeTitle: '',
                id: '',
                AttachmentUrl: '',
                AttachmentName: '',
                AttachmentSize: '',
                AttachmentType: '',
                isupload: false,
                serverTime: '',
                TemplateList: [],
                NoticeMain: 0,
                visible4: false,
                NoticeID: '',
                loading: false,
                ImportClick: false,
                isshowCommonWord: false,
                commonWordName: '',
                commonWordContent: '',
                commonWord: {},
                commonWordType: 'add',
                currentTemplateID: '',

                // 新选择对象
                isShowPickerDialog: false,
                selectedList: [],
                treeList: [],
                selectDeviceList: [],
                
                // 新增楼牌选择 2023-09-06  start
                equipVisible: false,
                equipList: [],
                chooseDeviceList: [],
                selectDeviceList: [],
                
                // 类型
                contentType: "1",
                // 是否公开
                noticeType: "1",

                editorValue: "",
            }
        )
    }
    //保存通知
    saveNotice() {
        let $this = this;
        let contentType = this.state.contentType

        if (this.state.noticeTitle.length == 0 || this.state.noticeTitle.trim().length == 0) {
            message.error("请输入标题")
            $('#notice-title .notice-create-span').css({
                color: 'red'
            })
            $('.notice-create-title').focus();
            $('#notice-title input').css({
                border: '1px solid #ff0000'
            })

            return;
        }
        if (this.state.editorValue || contentType != 1) {

        } else {
            message.error("通知内容不能为空")
            return
        }
        // if(this.state.selectedList.length == 0){
        //     message.error("选择用户不能为空")
        //     return
        // }

        let userList = []; 
        let receiverType = {
            receiverStr: [],
            high: [],
            junior: [],
            primary: [],
        }
        // 处理选择对象
        this.handleSelectList(this.state.selectedList.slice(0), userList, receiverType)
        // 去重
        for(let key in receiverType){
            receiverType[key] = [...new Set(receiverType[key])]
        }
        receiverType = JSON.stringify(receiverType)

        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
        let attachments = null
        if(this.state.AttachmentName){
            attachments = [{
                name: this.state.AttachmentName,
                size: this.state.AttachmentSize,
                url: this.state.AttachmentUrl,
                type: this.state.AttachmentType,
                orderNum: 0,
            }]
        }

        // 新增发布时楼牌列表2023-09-07
        let deviceList = [];
        let seleArr = this.state.selectDeviceList.concat([]);
        seleArr.forEach(item => {
            item.deviceType = "2"; // 固定传 2：楼牌
            item.deviceId = item.buildingBoardId;
            item.deviceName = item.buildingBoardName;
        })
        deviceList = seleArr

        let obj = {
            noticeId: this.state.editNoticeId,
            title: this.state.noticeTitle,
            content: contentType == 1? this.state.editorValue: "\u200B",
            userId: userInfo.userId,
            userName: userInfo.userName,
            identityCode: userInfo.identityCode,
            identityName: userInfo.userName,
            eduType: userInfo.productUseRange,
            attachments,
            receivers: userList,
            receiverType: receiverType,

            deviceList,
            contentType,
            noticeType: this.state.noticeType,
            eduId: sessionStorage.getItem("eduId"),
        }
        this.setState({
            loading: true
        })
        fetch.post({
            url: window.BasicProxy + 'api/notice/created/save',
            body: obj
        })
        .then((res) => {
            return res.json();
        }).then((json) => {
            if (json.code == 200 ) {
                $this.props.changeVisible(false);
                $this.props.getList()
                //    this.uploadFn();
                message.success('保存通知成功~', 3);
                
                this.setState({
                    NoticeMain: 0,
                })
                $('#file').val('');
            }
            this.setState({
                loading: false
            })
        })
    }
    // 发布
    publishNotice(){
      console.log("publishNotice");
        let $this = this;
        let contentType = this.state.contentType

        if (this.state.noticeTitle.length == 0 || this.state.noticeTitle.trim().length == 0) {
            message.error("请输入标题")
            $('#notice-title .notice-create-span').css({
                color: 'red'
            })
            $('.notice-create-title').focus();
            $('#notice-title input').css({
                border: '1px solid #ff0000'
            })

            return;
        }
        if (this.state.editorValue || contentType != 1) {

        } else {
            message.error("通知内容不能为空")
            return
        }
        if(this.state.selectedList.length == 0){
            message.error("选择用户不能为空")
            return
        }

        let userList = []; 
        let receiverType = {
            receiverStr: [],
            high: [],
            junior: [],
            primary: [],
        }
        // 处理选择对象
        this.handleSelectList(this.state.selectedList.slice(0), userList, receiverType)
        // 去重
        for(let key in receiverType){
            receiverType[key] = [...new Set(receiverType[key])]
        }
        receiverType = JSON.stringify(receiverType)

        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
        let attachments = null
        if(this.state.AttachmentName){
            attachments = [{
                name: this.state.AttachmentName,
                size: this.state.AttachmentSize,
                url: this.state.AttachmentUrl,
                type: this.state.AttachmentType,
                orderNum: 0,
            }]
        }

        // 新增发布时楼牌列表2023-09-07
        let deviceList = [];
        let seleArr = this.state.selectDeviceList.concat([]);
        seleArr.forEach(item => {
            item.deviceType = "2"; // 固定传 2：楼牌
            item.deviceId = item.buildingBoardId;
            item.deviceName = item.buildingBoardName;
        })
        deviceList = seleArr

        let obj = {
            noticeId: this.state.editNoticeId,
            title: this.state.noticeTitle,
            content: contentType == 1? this.state.editorValue: "\u200B",
            userId: userInfo.userId,
            userName: userInfo.userName,
            identityCode: userInfo.identityCode,
            identityName: userInfo.userName,
            eduType: userInfo.productUseRange,
            receivers: userList,
            receiverType: receiverType,
            attachments,

            deviceList,
            contentType,
            noticeType: this.state.noticeType,
            eduId: sessionStorage.getItem("eduId"),
        }
        this.setState({
            loading: true
        })
        fetch.post({
            url: window.BasicProxy + 'api/notice/created/release',
            body: obj
        })
        .then((res) => {
            return res.json();
        }).then((json) => {
            if (json.code == 200 ) {
                $this.props.changeVisible(false);
                $this.props.getList()
                //    this.uploadFn();
                message.success('发布通知成功~', 3);
                
                this.setState({
                    NoticeMain: 0,
                })
                $('#file').val('');
            }
            this.setState({
                loading: false
            })
        })
    }
    // 处理选择对象
    handleSelectList = (selected, userList, receiverType) => {
      selected.forEach(item => {
          if(item.identityCode){
              delete item.parent
              userList.push(item)
          }else{
              this.handleSelectList(item.children, userList, receiverType)
              return
          }
          
          receiverType.receiverStr.push(item.schoolName)
          // 高中
          if(['5', '9', '10'].includes(item.schoolLevel)){
              receiverType.high.push(item.schoolName)
          }
          // 初中
          if(['4', '8', '9', '10'].includes(item.schoolLevel)){
              receiverType.junior.push(item.schoolName)
          }
          // 小学
          if(['3', '8', '10'].includes(item.schoolLevel)){
              receiverType.primary.push(item.schoolName)
          }
      })
    }
    // 查询学校
    getSchool(){
        return new Promise((resolve) => {
            let obj = {
              eduId: sessionStorage.getItem("eduId") || "",
            }
            fetch.get({
                url: window.BasicProxy + 'api/commons/schools/receivers',
                params: obj
            }).then(res => res.json()).then(res => {
                if(res.code == 200){
                    let high = [],
                    junior = [],
                    primary = [],
                    treeList = [];
                    res.data.forEach(item => {
                        let obj = {}
                        let schoolName, schoolId
                        let schoolHigh = [],
                        schoolJunior = [],
                        schoolPrimary = [];
                        let totalCount = 0
                        item.forEach(child => {
                            schoolName = child.schoolName
                            schoolId = child.schoolId
                            child.label = child.identityName
                            child._itemId = child.identityId
                            child._total = child.userCount + '人'
                            totalCount = child.totalCount
                            // 高中
                            if(['5', '9', '10'].includes(child.schoolLevel)){
                                schoolHigh.push(child)
                            }
                            // 初中
                            if(['4', '8', '9', '10'].includes(child.schoolLevel)){
                                schoolJunior.push(child)
                            }
                            // 小学
                            if(['3', '8', '10'].includes(child.schoolLevel)){
                                schoolPrimary.push(child)
                            }
                        })
                        obj.label = schoolName
                        obj._groupId = schoolId
                        obj._total = totalCount + '人'
                        if(schoolHigh.length != 0){
                            let data = JSON.parse(JSON.stringify(obj))
                            data.children = schoolHigh
                            high.push(data)
                        }
                        if(schoolJunior.length != 0){
                            let data = JSON.parse(JSON.stringify(obj))
                            data.children = schoolJunior
                            junior.push(data)
                        }
                        if(schoolPrimary.length != 0){
                            let data = JSON.parse(JSON.stringify(obj))
                            data.children = schoolPrimary
                            primary.push(data)
                        }

                    })
                    treeList = [
                        {
                            label: '高中',
                            children: high,
                            _groupId: '1',
                        },
                        {
                            label: '初中',
                            children: junior,
                            _groupId: '2'
                        },
                        {
                            label: '小学',
                            children: primary,
                            _groupId: '3'
                        }
                    ]
                    resolve(treeList)
                }else{
                    resolve([])
                }
            })
        })
    }
    // 查询角色
    getRole(){
        return new Promise((resolve) => {
            let obj = {
              eduId: sessionStorage.getItem("eduId") || "",
            }
            fetch.get({
                url: window.BasicProxy + 'api/commons/schools/receivers',
                params: obj
            }).then(res => res.json()).then(res => {
                if(res.code == 200){
                    let schoolObj = {}; // identityCode: [有该身份的学校]
                    let identityCodeObj = {} // identityCode: identityName
                    let treeList = []
                    res.data.forEach(item => {
                        item.forEach(child => {
                            child._itemId = child.identityId
                            child._total = child.userCount + '人'
                            child.label = child.schoolName

                            if(schoolObj[child.identityCode]){
                                schoolObj[child.identityCode].push(child)
                            }else{
                                schoolObj[child.identityCode] = [child]
                                identityCodeObj[child.identityCode] = child.identityName
                            } 
                        })
                    })
                    for(let key in identityCodeObj){
                        let obj = {
                            label: identityCodeObj[key],
                            children: schoolObj[key],
                            _groupId: key
                        }
                        treeList.push(obj)
                    }
                    resolve(treeList)
                }else{
                    resolve([])
                }
            })
        })
    }
    // 显示选择对象弹窗
    showUserModal = async(type) => {
        let treeList = await this.getSchool()
        if(type === 0){ // 重选
            this.setState({
                isShowPickerDialog: true,
                selectedList: [],
                treeList
            })
        }else{ // 选择
            this.setState({
                isShowPickerDialog: true,
                // selectedList: this.state.selectedList,
                treeList
            })
        }
    }
    // 改变选择类型 按学校 按角色
    changeSelectType = async(type) => {
        let treeList = []
        if(type == 1){
            treeList = await this.getSchool()
        }else if(type == 2){
            treeList = await this.getRole()
        }
        this.setState({
            treeList
        })
    }
    // 选择对象回调
    userModalOnOk = (list) => {
        this.setState({
            selectedList: list,
            isShowPickerDialog: false
        })
    }
    // 删除某个选择用户
    deleteSelectedUser = (index) => {
        let selectedList = this.state.selectedList.slice(0)
        selectedList.splice(index, 1)
        this.setState({
            selectedList
        })
    }
    render() {
        // console.log(this.props.NoticeMain)
        function showhtml(htmlString) {
            var html = { __html: htmlString };
            return <div className="Template-content" dangerouslySetInnerHTML={html}></div>;
        }
        
        return (
            <div className='notice-create' >
                
                <Modal
                    className={'notice-create-modal'}
                    height={ this.state.isFrame == 'true'? '100%' : this.state.iFrame ? 720 : 720}
                    title="发布通知"
                    visible={this.props.visible}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    onCancel={() => this.CloseNotice()}
                    centered
                    footer={[<Button key='test' onClick={() => { this.CloseNotice() }}>取消</Button>,
                    <Button className='notice-save-bottom' style={{marginRight: 4}} key='test3' onClick={() => { this.saveNotice() }}>保存</Button>, 
                    <Button key='test1' onClick={() => { this.publishNotice() }}>发布</Button>, 
                    <span className='notice-create-bottom3' key='test2' onClick={() => { this.onoK4() }}>预览</span>]}
                    width={this.state.isFrame == 'true'? '100%' :this.state.iFrame ? '800px' : '1200px'}
                    maskClosable={false}
                // destroyOnClose={false}
                // wrapClassName='notice-create-Modal'  
                >
                    <Scrollbars
                        renderThumbHorizontal={() => { return <div style={{ display: 'none' }}></div> }}
                        style={ this.state.isFrame? { width: 1000, height: 620 } : this.state.iFrame ? { width: 800, height: 450 } : { width: 1200, height: 620 }}
                    >
                        <div className="warn-alert" style={{display: (this.state.alertShow? "block": "none")}}>
                            <span className={this.state.alertType === 1? "successlogo": this.state.alertType === 2? "errorlogo": "warnlogo"}></span>
                            {this.state.alertText}
                        </div>
                        
                        <div style={{ padding: '12px' }} className="notice-body-container">
                            <label id="notice-title"><span className="notice-create-span">标题:</span>
                            <input maxLength='50' className="notice-create-title" placeholder="请输入通知标题" 
                            value={this.state.noticeTitle} onChange={(e) => { this.changeNoticeTitle(e) }} 
                            onBlur={this.checkContent}/><b className="notice-title-length" >{this.state.noticeTitle.length}/50</b></label>
                            <div></div>
                            <span className="notice-create-span">
                                类型:
                            </span>
                            <Radio.Group value={this.state.contentType} onChange={this.changeContentType}>
                              <Radio value="1">文本</Radio>
                              <Radio value="2">音/视频</Radio>
                            </Radio.Group>
                            <div style={{ 
                              display: this.state.contentType == 1? "block": "none"
                            }}>
                              <span className="create-content">
                                正文:
                              </span>
                              <WangEditor id='editor'
                                  getHtmlContent={(html) => {
                                    this.setState({editorValue: html && html !== '<p><br></p>' ? html : ''})
                                  }} value={this.state.editorValue}
                              />
                            </div>
                            <div className={this.state.isFrame=="true"?"upload-success-div isFrame":'upload-success-div'}>
                                <span>  {this.state.contentType == 1? "附件": "音/视频"}:</span> 
                                {this.state.isupload == 'true' ? 
                                <span className='upload-success-span upload-success-span1'>正在上传，请稍等~</span> :
                                !this.state.AttachmentUrl ? 
                                    <>
                                      <span className='upload-span'>
                                        <b onClick={() => { $('#file').click() }}>添加{this.state.contentType == 1? "附件": "音/视频"}</b> [最大50M，{this.state.contentType == 1? "支持上传所有类型文件": "支持上传音频、视频"}] 
                                      </span>
                                      <form id="uploadImg" >
                                          <input 
                                          name="file" 
                                          type="file" 
                                          id="file" 
                                          accept={this.state.contentType == 1? "*": ".AVI,.ASF,.WMV,.AVS,.FLV,.MKV,.MOV,.3GP,.MP4,.MPG,.MPEG,.DAT,.OGM,.VOB,.RM,.RMVB,.TS,.TP,.IFO,.NSV,.MP3,.AAC,.WAV,.WMA,.CDA,.FLAC,.M4A,.MID,.MKA,.MP2,.MPA,.MPC,.APE,.OFR,.OGG,.RA,.WV,.TTA,.AC3,.DTS"} 
                                          onChange={(e) => { this.uploadFile() }} 
                                          />
                                      </form>
                                    </> : 
                                    <>
                                      <span className='upload-success-span' onClick={() => {this.prevFile(this.state.AttachmentUrl)}} style={{ cursor: "pointer", left: this.state.contentType == 1? "39px": "55px" }}>
                                          <i className={this.state.AttachmentName.slice(this.state.AttachmentName.lastIndexOf('.') + 1, this.state.AttachmentName.length)}></i>
                                          <b title={this.state.AttachmentName}>
                                              <b>
                                                  <b className="upload-file-type1">{this.state.AttachmentName.slice(0, this.state.AttachmentName.lastIndexOf('.'))}</b>
                                                  <b className="upload-file-type">{this.state.AttachmentName.slice(this.state.AttachmentName.lastIndexOf('.'), this.state.AttachmentName.length)}</b>
                                              </b>
                                          </b>
                                          <b>{this.state.AttachmentSize / 1024 / 1024 > 1 ? '[' + (this.state.AttachmentSize / 1024 / 1024).toFixed(2) + 'MB]' : '[' + (this.state.AttachmentSize / 1024).toFixed(0) + 'KB]'}</b>
                                          <b onClick={this.uploadDel}>×</b>
                                      </span>
                                      {
                                        this.state.contentType == 1 && this.state.selectDeviceList.length > 0?
                                        <span style={{ color: "#999", fontSize: "12px", marginLeft: "10px" }}>(注：学校楼牌不支持查看附件)</span>:
                                        ""
                                      }
                                    </>
                                }
                            </div>
                            <span className="notice-create-span" style={{marginLeft: 27}}>
                                是否公开:
                            </span>
                            <Radio.Group value={this.state.noticeType} onChange={this.changeNoticeType}>
                              <Radio value="0">否</Radio>
                              <Radio value="1">是</Radio>
                            </Radio.Group>
                            <span style={{color: "#999"}}>(默认公开，游客可查看公开信息)</span>
                            {this.state.isFrame == 'true'?(<div style={{height: '1px', backgroundColor: '#ffffff', opacity: '0.14',margin: '0 41px'}}></div>):(<div style={{height: '1px', backgroundColor: '#e6e6e6', margin: '0 41px'}}></div>)}
                            <div className="select-option">
                                <span className="option-title">选择用户:</span>
                                <div className="selected-list">
                                    {
                                        this.state.selectedList.length > 0?
                                        this.state.selectedList.map((item, index)=>{
                                            return (
                                                <div className="selected-one" key={index}>
                                                    {item.label}
                                                    {/* {
                                                        item.UserNameList?
                                                        <span style={{color: '#999999'}}>
                                                            ({item.UserNameList.join(',')})
                                                        </span>:
                                                        ""
                                                    } */}
                                                    
                                                    <span className="deletelogo" onClick={()=>this.deleteSelectedUser(index)}></span>
                                                </div>
                                            )
                                        }):
                                        ""
                                    }
                                </div>
                                    
                                <span className="option-btn" onClick={()=>this.showUserModal(1)}>选择</span>
                                {
                                    this.state.selectedList.length > 0?
                                    <span className="option-btn" onClick={()=>this.showUserModal(0)}>重选</span>:
                                    ""
                                } 
                            </div>

                            <div className="select-option">
                                <span className="option-title">选择楼牌:</span>
                                <div className="selected-list">
                                    {
                                        this.state.selectDeviceList.length > 0?
                                        this.state.selectDeviceList.map((item, index) => {
                                          if (index > 2) return;
                                          return (
                                              <div className="selected-one">
                                                  {item.schoolName + '-' + item.buildingBoardName}
                                                  <span onClick={() => this.delSelect(index)} className="deletelogo"></span>
                                              </div>
                                          )
                                      }):
                                        ""
                                    }
                                </div>
                                    
                                <span className="option-btn" onClick={()=> this.openDeviceModal()}>选择</span>
                                {
                                    this.state.selectDeviceList.length > 0?
                                    <span className="option-btn" onClick={()=> this.reChooseDevice()}>重选</span>:
                                    ""
                                } 
                            </div>

                        </div>
                    </Scrollbars>
                </Modal>

                {/* 预览 */}
                <Modal className='notice-view-model'
                    title="预览通知"
                    visible={this.state.visible4}
                    // onOk={this.handleOk}
                    onCancel={this.handleCancel4}
                    footer={null}
                    width={this.state.iFrame ? '800px' : '1166px'}
                    centered
                // destroyOnClose={true}
                >
                    <Scrollbars style={this.state.iFrame ? { width: 800, height: 500 } : { width: 1168, height: 580 }}>
                        <div style={{ padding: '24px' }}>
                            <h1 style={{ textAlign: 'center', color: '#333333', marginBottom: '10px' }}>{this.state.noticeTitle.length > 0 ? this.state.noticeTitle : '您还没有输入通知标题哦~'}</h1>
                            <p className='notice-details-message' style={{color: '#999999'}}><span> <i className='people-img'> </i>{decodeURIComponent(sessionStorage.getItem('userName') || "--")}</span><span><i className='timer-img'></i>{this.state.serverTime}</span></p>
                            <p className='notice-details-border'></p>
                            <div className='notice-contect' style={{color: '#333333'}}> {this.state.visible4 ? showhtml(this.state.editorValue) : ''}</div>
                            {this.state.AttachmentName ? <div className="notice-down-box">
                                <p><i></i>附件下载</p>
                                <div className="notice-down-message">
                                    <span className={this.state.AttachmentName.slice(this.state.AttachmentName.lastIndexOf('.') + 1, this.state.AttachmentName.length) + ' uploadType-img'} ></span>
                                    <p title={this.state.AttachmentName.length > 60 ? this.state.AttachmentName : ''}>{this.state.AttachmentName.length > 60 ? this.state.AttachmentName.slice(0, 58) + '..' : this.state.AttachmentName}  <span>{(this.state.AttachmentSize / 1024 / 1024) >= 1 ? '[' + (this.state.AttachmentSize / 1024 / 1024).toFixed(1) + 'MB]' : '[' + (this.state.AttachmentSize / 1024).toFixed(1) + 'KB]'}</span></p>
                                    {/* <a  download={this.state.AttachmentName} onClick={()=>{this.downFile(this.state.AttachmentUrl) }}>下载</a> */}
                                    <b style={{display:'none'}} className='down-file' href={this.state.AttachmentUrl.indexOf('.mp4') === -1 && this.state.AttachmentUrl.indexOf('.mp4') === -1 ? this.state.AttachmentUrl : this.state.AttachmentUrl + '?filename=' + this.state.AttachmentName.slice(0, -4)} download={this.state.AttachmentName} onClick={() => { this.downFile(this.state.AttachmentUrl, this.state.AttachmentName) }}>下载</b>        </div>
                            </div> : ''}
                        </div>  </Scrollbars>
                </Modal>
                
                {/* 新发布对象 */}
                <LgPickerDialog
                title="选择用户"
                visible={this.state.isShowPickerDialog}
                selectedList={this.state.selectedList}
                treeList={this.state.treeList}
                changeSelectType={(type) => {this.changeSelectType(type)}}
                onClose={() => {this.setState({isShowPickerDialog: false})}}
                onOk={(list) => this.userModalOnOk(list)}
                ></LgPickerDialog>

                {/* 楼牌 */}
                <Modal
                    width={900}
                    visible={this.state.equipVisible}
                    title="选择楼牌"
                    zIndex={1004}
                    bodyStyle={{
                        height: 570,
                        padding: "0"
                    }}
                    className="select-equip"
                    footer={null}
                    onCancel={() => this.cancelSle()}
                >
                    <div className='select-equip-content'>
                        <div className='select-equip-left'>
                            <Scrollbars
                                autoHeightMax={460}
                                style={{
                                    minHeight: 400
                                }}
                            >
                                {
                                    this.state.chooseDeviceList.map((item, index) => {
                                        let findIndex = this.state.equipList.findIndex(itm => itm.schoolId === item.schoolId);
                                        return (
                                            <div key={index} className="select_item">
                                                <span className="tabName ellipsis" title={item.schoolName + "-" + item.buildingBoardName}
                                                >{item.schoolName + "-" + item.buildingBoardName}</span>
                                                <span className="deleteIcon" onClick={() => this.deleteDevice(index, this.state.equipList[findIndex])}></span>
                                            </div>
                                        )
                                    })
                                }
                            </Scrollbars>
                        </div>
                        <div className='select-equip-right'>
                            <Scrollbars
                                autoHeightMax={480}
                                style={{
                                    minHeight: 400
                                }}
                            >
                                {
                                    this.state.equipList.map((item, index) => {
                                        return (
                                            <>
                                                <div className="list-one" onClick={() => this.showEquipList(item.showEquip, index)}>
                                                    <span className="listlogo buildlogo"></span>
                                                    <span title={item?.schoolName}> {item?.schoolName}</span>
                                                    {/* <span className={item.showEquip ? "uplogo" : "downlogo"}></span> */}
                                                </div>
                                                {
                                                    item.showEquip && item.buildingBoardList ?
                                                        <div style={{ paddingLeft: '41px' }}>
                                                            {
                                                                item.buildingBoardList.length > 0 ?
                                                                    <div className="allChecked" onClick={() => this.allChecked(item, index)}>
                                                                        <span className={"allCheckedlogo " + (item?.buildSign ? item?.buildSign : "")}></span>
                                                                        全选
                                                                    </div> :
                                                                    <div style={{
                                                                        display: 'inline-block',
                                                                        height: '120px',
                                                                        position: 'relative',
                                                                        top: '60px',
                                                                        left: '93px',
                                                                        color: '#999999'
                                                                    }}>暂无可选楼牌</div>
                                                            }
                                                            <ul className="child-list">
                                                                {
                                                                    item.buildingBoardList.length > 0 ?
                                                                        item.buildingBoardList.map((itm, idx) => {
                                                                            let isExist = false;
                                                                            this.state.chooseDeviceList.forEach((child) => {
                                                                                if (child.buildingBoardId === itm.buildingBoardId && child.schoolId === itm.schoolId) {
                                                                                    isExist = true;
                                                                                }
                                                                            })
                                                                            return (
                                                                                <li key={idx} onClick={() => this.chooseDevice(itm, item)}>
                                                                                    <span className={"checklogo " + (isExist ? "active" : "")}></span>
                                                                                    {itm.buildingBoardName}
                                                                                </li>
                                                                            )
                                                                        }) :
                                                                        ""
                                                                }
                                                            </ul>
                                                        </div>
                                                        : ''
                                                }
                                                <div className="list-line"></div>
                                            </>
                                        )
                                    })
                                }
                            </Scrollbars>
                        </div>
                    </div>
                    <div className="select_footer">
                        <span className='sureBtn' onClick={() => this.confirmSle()}>确定</span>
                        <span className='closeBtn' onClick={() => this.cancelSle()}>取消</span>
                    </div>
                </Modal>

                {this.state.loading ?
                <div style={{
                    width: '100%',
                    height: '100%',
                    position: 'absolute',
                    top: '0',
                    left: '0',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: '9999'
                }}>
                   <Spin size="large" /> 
                </div>
                :
                ''}
                
            </div>
        )
    }
}

export default CreateNotice;